package dictimpl

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"go-caipu/pkg/services/admin/dict"
	"go-caipu/pkg/services/admin/dict/models"
	"go-caipu/pkg/services/dto"
	"gorm.io/gorm"
	"time"
)

// GetSysDictDataPage 查询参数值列表
func (s sqlStore) GetSysDictDataPage(ctx context.Context, cmd dict.GetSysDictDataPageCommand) (data []dict.SysDictData, num int64, err error) {
	var items []models.SysDictData
	err = s.db.Model(&models.SysDictData{}).Scopes(
		dto.MakeCondition(cmd.GetNeedSearch()),
		dto.Paginate(cmd.GetPageSize(), cmd.GetPageIndex()),
	).Preload("CreateUser").Preload("UpdateUser").Find(&items).Limit(-1).Offset(-1).Count(&num).Error
	if err != nil {
		return
	}
	for _, v := range items {
		data = append(data, ConvertToDataDTO(v))
	}
	return
}
func ConvertToDataDT(model dict.SysDictData, cmd *models.SysDictData) {
	cmd.DictCode = model.DictCode
	cmd.DictSort = model.DictSort
	cmd.DictLabel = model.DictLabel
	cmd.DictValue = model.DictValue
	cmd.CssClass = model.CssClass
	cmd.ListClass = model.ListClass
	cmd.Default = model.Default
	cmd.DictType = model.DictType
	cmd.DictID = model.DictId
	cmd.Status = model.Status
	cmd.Remark = model.Remark
}

func ConvertToDataDTO(model models.SysDictData) dict.SysDictData {
	result := dict.SysDictData{
		DictCode:         model.DictCode,
		DictSort:         model.DictSort,
		DictLabel:        model.DictLabel,
		DictValue:        model.DictValue,
		CssClass:         model.CssClass,
		ListClass:        model.ListClass,
		Default:          model.Default,
		DictType:         model.DictType,
		DictId:           model.DictID,
		Status:           model.Status,
		Remark:           model.Remark,
		CreatedAt:        model.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt:        model.UpdatedAt.Format("2006-01-02 15:04:05"),
		CreateUserString: model.CreateUser.NickName,
		UpdateUserString: model.UpdateUser.NickName,
		ControlBy:        model.ControlBy,
	}

	return result
}
func (s sqlStore) GetDictData(ctx context.Context, cmd dict.GetSysDictDataCommand) (result dict.SysDictData, err error) {
	var data models.SysDictData
	err = s.db.Model(&data).First(&data, cmd.Id).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New(fmt.Sprintf("DictDataId：%d record Not found", cmd.Id))
		return
	}
	if err != nil {
		s.logger.Log(fmt.Sprintf("get  dict=%d  error:%s", cmd.Id, err.Error()))
		return
	}
	return ConvertToDataDTO(data), nil
}
func (s sqlStore) InsertDictData(ctx context.Context, cmd dict.SysDictData) (err error) {
	tx := s.db.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	var data models.SysDictData
	ConvertToDataDT(cmd, &data)
	data.CreatedAt = time.Now()
	data.CreateBy = cmd.CreateBy
	err = tx.Create(&data).Error
	if err != nil {
		s.logger.Log(fmt.Sprintf("insert  dict  error:%s", err.Error()))
		return err
	}
	return nil
}
func (s sqlStore) UpdateDictData(ctx context.Context, cmd dict.SysDictData) (err error) {
	tx := s.db.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	//查询当前部门名称是否存在
	var data models.SysDictData
	err = s.db.Model(&data).First(&data, cmd.DictCode).Error
	if err != nil {
		s.logger.Log(fmt.Sprintf("check dictDatalabel :%s is exists error:%s", cmd.DictLabel, err.Error()))
		return err
	}
	ConvertToDataDT(cmd, &data)
	data.UpdatedAt = time.Now()
	data.UpdateBy = cmd.UpdateBy

	err = tx.Save(&data).Error
	if err != nil {
		s.logger.Log(fmt.Sprintf("update  dict  error:%s", err.Error()))
		return err
	}
	return nil
}
func (s sqlStore) RemoveDictData(ctx context.Context, cmd dict.RemoveSysDictDataCommand) (err error) {
	tx := s.db.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	var data models.SysDictData
	err = tx.Model(&models.SysDictData{}).Delete(&data, cmd.Ids).Error
	if err != nil {
		return err
	}
	return
}

// GetDictDataOptions get dict data option
func (s sqlStore) GetDictDataOptions(ctx context.Context, dictType string) (data []dict.Options, err error) {
	var dictTypeModel models.SysDictType
	err = s.db.Model(&models.SysDictType{}).Where("dict_type = ?", dictType).First(&dictTypeModel).Error
	if err != nil {
		return nil, err
	}

	var items []models.SysDictData
	err = s.db.Model(&models.SysDictData{}).Where("dict_id", dictTypeModel.DictId).Find(&items).Error
	if err != nil {
		return
	}

	for _, v := range items {
		// 过滤掉状态为禁用的
		if v.Status == 0 {
			continue
		}
		//转换为数字或者字符
		var value int64
		var dictData any
		dictData = v.DictValue
		if err := json.Unmarshal([]byte(v.DictValue), &value); err == nil {
			dictData = value
		}
		
		data = append(data, dict.Options{Color: v.CssClass, Label: v.DictLabel, Value: dictData})
	}
	return
}
